/**
 * 
 */
package org.dragonfire.dasm.directives;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;

import org.dragonfire.dasm.Command;
import org.dragonfire.dasm.CompileException;
import org.dragonfire.dasm.Listing;
import org.dragonfire.dasm.DirectiveManager.Directive;

/**
 * Adds an entry to the export file
 * 
 * @author Darth Android
 * @version 2.0
 */
// TODO finish documentation
public class Export extends Directive {

	private PrintWriter exportFile = null;

	/**
	 * {@inheritDoc}
	 */
	@Override
	public ArrayList<Listing> pass1(Command c) {
		ArrayList<Listing> list = new ArrayList<Listing>();
		Listing l = new Listing(0, c);
		list.add(l);
		return list;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void pass2(Listing list, Command c) {
		if (exportFile == null) {
			String exportFileName = getParam("exportfile");
			if (exportFileName == null) {
				exportFileName = getParam("sourcefile").replaceAll(".*[\\\\\\/]", "").replaceAll("\\..*", "") + ".inc";
			}
			try {
				exportFile = new PrintWriter(exportFileName);
			} catch (FileNotFoundException fnfe) {
				throw new CompileException("ERROR_DEST_UNWRITABLE");
			}
		}
		if (exportFile != null) {
			for (int i = 0; i < c.getParams().length; i++) {
				String param = c.getParams()[i];
				if (getCompiler().getBooleanParam("compat-tasm") == false)
					param = evalString(param);
				String value = getCompiler().getDefine(param);
				exportFile.println("#DEFINE \"" + param + "\"," + value);
				exportFile.flush();
			}
		}
	}
}
